package cn.tedu.confirm;

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;

//批量发布确认模式
public class MoreConfirm {
    public static void main(String[] args) throws Exception{
        //1.通过连接工厂配置rabbitmq的连接信息
        ConnectionFactory cf = new ConnectionFactory();
        cf.setHost("127.0.0.1");
        cf.setPort(5672); //客户端端口，5672是默认端口，可以省略
        cf.setUsername("guest");
        cf.setPassword("guest");
        //2.创建tcp和channel
        Connection nc = cf.newConnection();
        Channel cc = nc.createChannel();
        //3.使用随机队列名
        String queueName = cc.queueDeclare().getQueue();
        //开启发布确认
        cc.confirmSelect();
        long start = System.currentTimeMillis();
        for (int i = 1; i <= 100; i++) {
            String msg = "消息:"+i;
            cc.basicPublish("",queueName,null,msg.getBytes());
            //每发送10条数进行一次确认
            if(i%10 == 0){
                int prevIndex = i-9;
                String tempMsg = "消息:"+prevIndex;
                boolean flag = cc.waitForConfirms();
                if(flag)
                    System.out.println("("+tempMsg+"-"+msg+")"+"发布成功");
            }
        }
        long end = System.currentTimeMillis();
        System.out.println("发送100条消息数据使用的时间:"+(end-start));
    }
}
